﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using A2DFramework.XmlService;

namespace A2DFramework.EsbService.DistributedEsb.SessionSupport
{
    public class SessionContext : ISessionContext
    {
        private string SessionID { get; set; }
        private string SessionItems { get; set; }
        private bool loaded=false;
        private List<KeyValuePair<string, object>> kvs = new List<KeyValuePair<string, object>>();

        public SessionContext(string sessionId, string sessionItems)
        {
            this.SessionID = sessionId;
            this.SessionItems = sessionItems;
            this.loaded = false;
        }
        private void LoadSession()
        {
            if (this.loaded)
                return;

            if (this.SessionID == null || this.SessionID.Trim().Length == 0)
            {
                this.loaded = true;
                return;
            }
            if (this.SessionItems == null || this.SessionItems.Trim().Length == 0)
            {
                this.loaded = true;
                return;
            }

            object o = SerializeUtils.BinaryDeserializeFromBase64(this.SessionItems);
            if (o != null)
                kvs = (List<KeyValuePair<string, object>>)o;
            this.loaded = true;
        }

        public object GetWebSession(string key)
        {
            LoadSession();

            foreach (var item in this.kvs)
                if (item.Key == key)
                    return item.Value;

            return null;
        }
    }
}
